跳到主要内容

安装并使用 Docker

安装 Docker

Linux

  • 在 Linux 上安装 Docker 官方推荐使用 shell 脚本进行安装最新版,但是通常因为国内不能直接访问脚本中的下载地址,为了简单也可以直接使用 apt 等包管理器进行安装
  • Docker 安装时,会注册一个 docker 的一个服务,命令行中的 docker CLI命令与 docker daemon(Docker Engine) 进行交互

Shell 脚本安装

curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh

apt 安装

这里注意不是 docker,而是 docker.io

apt install -y docker.io

Windows 和 MacOS

直接去官网下载对应的安装包即可 ** https://www.docker.com/ **

  • 使用安装包安装时会默认安装 Engine 和 CLI
  • MacOS使用 Homebrew 安装时
brew install docker

只会安装 CLI,而不带有 Engine,还是需要去下载 Desktop

  • 运行 Docker CLI 时,要确保 Docker desktop 正在运行,否则会出现
Cannot connect to the Docker daemon

Docker, Hello World!

安装完 Docker 之后,就可以进行 Docker 的第一次使用 - hello world

docker run hello-world

输出如下

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (arm64v8)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

拉取并进入 Ubuntu 容器

  • 拉取镜像
docker pull ubuntu
  • 运行一个 Ubuntu 容器,并进入 Shell
docker run -it ubuntu bash
  • 查看容器内系统信息
cat /etc/os-release

可以看到成功输出了 Ubuntu 的版本信息

PRETTY_NAME="Ubuntu 24.04.3 LTS"
NAME="Ubuntu"
VERSION_ID="24.04"
VERSION="24.04.3 LTS (Noble Numbat)"
VERSION_CODENAME=noble
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=noble
LOGO=ubuntu-logo

现在你就可以尝试跑一下别人的容器了!

在开源社区中,有非常多的优秀的容器镜像可以直接使用,比如说 MySQL、Nginx、Redis 等等